package collectionDemo;

import org.apache.log4j.Logger;
import org.junit.Test;

import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author Ajie
 * @date 2020-07-03
 * @function
 */
public class LinkedBlockQueue_Demo {
    private static final Logger logger =  Logger.getLogger(LinkedBlockQueue_Demo.class);

//    public static void main(String[] args) {
//        testOfferQueue();
//    }

//    @Test
    public static void testOfferQueue(){
        LinkedBlockingDeque<String> strQueue = new LinkedBlockingDeque<>(200);

        for (int i = 0; i < 10; i++) {
            logger.info("testOfferQueue: "+strQueue.offer(String.valueOf(i)));
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 10; i < 110; i++) {
                    logger.info("testOfferQueue: "+strQueue.offer(String.valueOf(i)));
                    try {
                        System.out.println("add--size  "+strQueue.size());
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();



        new Thread(new Runnable() {
            @Override
            public void run() {

                Iterator<String> iterator = strQueue.iterator();
                while (iterator.hasNext()){
                    iterator.remove();
                    try {
                        System.err.println("remove--size  "+strQueue.size());
                        Thread.sleep(new Random(200).nextInt());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    @Test
    public void testRemoveQueue(){
        LinkedBlockingDeque<String> strQueue = new LinkedBlockingDeque<>(100);

        for (int i = 0; i < 10; i++) {
            strQueue.offer(String.valueOf(i));
        }

        Iterator<String> iterator = strQueue.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            if (next.equals("3")){
                iterator.remove();
            }
        }

        Iterator<String> iterator2 = strQueue.iterator();
        while (iterator2.hasNext()){
            String next = iterator2.next();
           logger.info("testRemoveQueue: "+next);
        }


    }


}
